//
//  SSLAudioPlayer.m
//  SSLAudioPlay
//
//  Created by 恒达的mini on 2017/6/13.
//  Copyright © 2017年 孙世龙. All rights reserved.
//

#import "SSLAudioPlayer.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>

#define updateRate           0.05f     //进度刷新频率

@interface SSLAudioPlayer(){
    BOOL       enterBgPlaying;//是否后台播放
}

@end


@implementation SSLAudioPlayer

static SSLAudioPlayer *instance = nil;
+(instancetype)sharedInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        instance = [[self alloc] init];
        [instance addNotification];
    });
    
    return instance;
}
- (void)addNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(audioRouteChangeListenerCallback:)
                                                 name:AVAudioSessionRouteChangeNotification object:nil];//设置通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(backFromBackground)
                                                 name:UIApplicationDidBecomeActiveNotification object:nil];//设置通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(backToBackground)
                                                 name:UIApplicationDidEnterBackgroundNotification object:nil];//设置通知
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(audioInterruption)
                                                 name:AVAudioSessionInterruptionNotification object:nil];//设置通知
}
#pragma mark -------- Interrupt Methods --------

// 判断耳机拔插事件的
- (void)audioRouteChangeListenerCallback:(NSNotification*)notification {
    NSDictionary *interuptionDict = notification.userInfo;
    NSInteger routeChangeReason = [[interuptionDict valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
    switch (routeChangeReason) {
        case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
            NSLog(@"AVAudioSessionRouteChangeReasonNewDeviceAvailable");
            NSLog(@"耳机插入");
            break;
            
        case AVAudioSessionRouteChangeReasonCategoryChange:            // called at start - also when other audio wants to play
            NSLog(@"AVAudioSessionRouteChangeReasonCategoryChange");
            break;
            
        case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"AVAudioSessionRouteChangeReasonOldDeviceUnavailable");
                NSLog(@"耳机拔出，停止播放操作");
                [self backToBackground];
            });
            break;
    }
}

- (void)audioInterruption
{
    if (_playStatus == kPlay_Status_Playing) {
        [self audioControlAction];
    }
}

- (void)backFromBackground
{
    if (enterBgPlaying == YES) {
        [self audioControlAction];
    }
}

- (void)backToBackground
{
    if (_playStatus == kPlay_Status_Playing) {
        [self audioControlAction];
        enterBgPlaying = YES;
    }
    else {
        enterBgPlaying = NO;
    }
}

- (void)audioControlAction
{
    if (_player == nil) {
        return;
    }
    if (_playStatus == kPlay_Status_Playing) {
        [self audio_pause];
        _playStatus = kPlay_Status_Pause;
        
        if([self.delegate respondsToSelector:@selector(updatePlayBtnStatus:)]) {
            [self.delegate updatePlayBtnStatus:NO];
        }
    }else {

        [self audio_play];
        _playStatus = kPlay_Status_Playing;
        
        if([self.delegate respondsToSelector:@selector(updatePlayBtnStatus:)]) {
            [self.delegate updatePlayBtnStatus:YES];
        }
    }
}

- (void)initAudioPlayerByUrl:(NSURL*)audioUrl{
    NSError *error;
    NSData *data = [[NSData alloc] initWithContentsOfURL:audioUrl];
    if ([[NSString stringWithFormat:@"%@",audioUrl] hasPrefix:@"http"]) {
        _player = [[AVAudioPlayer alloc] initWithData:data error:&error];//网络音频
    }else{
        _player = [[AVAudioPlayer alloc] initWithContentsOfURL:audioUrl error:&error];//本地音频
    }
    _player.delegate = self;
}
//切换
- (void)restAudioPathWith:(NSURL*)newPath{
    [_player pause];
    if (_player) {
        _player = nil;
    }
    [self initAudioPlayerByUrl:newPath];
}
//获取总时长
- (float)getAudioDuration{
    return _player.duration;
}
//获取当前时间
- (float)getCurrentTime{
    return _player.currentTime;
}
//获取固定格式
- (NSString*)getTimeByFormateBy:(int)totalSecond{
    int seconds = totalSecond % 60;
    int minutes = (totalSecond / 60) % 60;
    int hours = totalSecond / 3600;
    
    return [NSString stringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds];
}
//转换成当前时刻
- (NSString *)timeFormatted1:(int)totaSecond
{
    NSDate  *date = [NSDate dateWithTimeIntervalSince1970:totaSecond];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
    NSLog(@"enddate=%@",localeDate);
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy:MM:dd HH:mm:ss"];
    NSString *currentDateStr = [formatter stringFromDate:localeDate];
    
    return currentDateStr;
}
//预加载音频
- (BOOL)audio_prepare{
    
    if ([_player prepareToPlay]) {
        return YES;
    }
    _playStatus = kPlay_Status_Unknown;
    return NO;
}
//播放
- (void)audio_play{
    if (_player.playing) {
        return;
    }
    //开始计时，更新播放进度
    self.timer = [NSTimer scheduledTimerWithTimeInterval:updateRate
                                                  target:self
                                                selector:@selector(updateAudioProgress)
                                                userInfo:nil
                                                 repeats:YES];
    [self.timer fire];
    
    [_player play];
    _playStatus = kPlay_Status_Playing;
}
//暂停
- (void)audio_pause{
    [self.timer invalidate];
    
    if (_player.playing) {
        
        [_player pause];
        _playStatus = kPlay_Status_Pause;
    }
}
//停止播放
- (void)audio_revert{
    [self.timer invalidate];
    self.timer = nil;
    [_player stop];
    _player = nil;
    _playStatus = kPlay_Status_Stop;
}
//更新进度
- (void)updateAudioProgress{
    float progress = (float) (_player.currentTime / _player.duration);
    if (self.delegate&&[self.delegate respondsToSelector:@selector(backAudioPlayProgress:)]) {
        [self.delegate backAudioPlayProgress:progress];
    }
}
#pragma mark AVAudioPlayerDelegate method
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    [self.timer invalidate];
    if (self.delegate&&[self.delegate respondsToSelector:@selector(backAudioPlayFinish)]) {
        [self.delegate backAudioPlayFinish];
    }
}

@end
